<template>
  <div class="banner-type-icon-v2" style="position:relative;width:100%;height:8rem;" :style="{ pointerEvents: isEditMode ? 'none' : 'auto' }" @click.stop="handleEditModeClick">
    <swiper autoplay indicator-dots circular style="width:100%;height:100%;">
      <swiper-item v-for="(group, idx) in bannerGroups" :key="idx">
        <div style="position:relative;width:96%;height:100%;margin: 8px 0 0  8px">
          <!-- 完整布局 -->
          <template v-if="group.length === groupSize">
            <!-- [1,1] -->
            <template v-if="isType1">
              <div class="rect big" style="position:absolute;left:2%;top:4%;width:46%;height:92%;overflow:hidden;">
                <img v-if="group[0]" :src="getFullImgUrl(group[0].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
              <div class="rect big" style="position:absolute;right:2%;top:4%;width:46%;height:92%;overflow:hidden;">
                <img v-if="group[1]" :src="getFullImgUrl(group[1].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
            </template>
            <!-- [2,1] -->
            <template v-else-if="isType2">
              <div class="rect small" style="position:absolute;left:2%;top:4%;width:28%;height:44%;overflow:hidden;">
                <img v-if="group[0]" :src="getFullImgUrl(group[0].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
              <div class="rect small" style="position:absolute;left:2%;bottom:4%;width:28%;height:44%;overflow:hidden;">
                <img v-if="group[1]" :src="getFullImgUrl(group[1].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
              <div class="rect big" style="position:absolute;right:2%;top:4%;width:66%;height:92%;overflow:hidden;">
                <img v-if="group[2]" :src="getFullImgUrl(group[2].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
            </template>
            <!-- [1,2] -->
            <template v-else-if="isType3">
              <div class="rect big" style="position:absolute;left:2%;top:4%;width:66%;height:92%;overflow:hidden;">
                <img v-if="group[0]" :src="getFullImgUrl(group[0].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
              <div class="rect small" style="position:absolute;right:2%;top:4%;width:28%;height:44%;overflow:hidden;">
                <img v-if="group[1]" :src="getFullImgUrl(group[1].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
              <div class="rect small" style="position:absolute;right:2%;bottom:4%;width:28%;height:44%;overflow:hidden;">
                <img v-if="group[2]" :src="getFullImgUrl(group[2].thumb)" style="width:100%;height:100%;object-fit:cover;" />
              </div>
            </template>
            <!-- [1] 或其它 -->
            <template v-else>
              <img :src="getFullImgUrl(group[0].thumb)" style="width:96%;height:100%;object-fit:cover;margin: 10px 0 0 10px" />
            </template>
          </template>
          <!-- 不足一组，单图铺满 -->
          <template v-else>
            <img :src="getFullImgUrl(group[0].thumb)" style="width:100%;height:100%;object-fit:cover;" />
          </template>
        </div>
      </swiper-item>
    </swiper>
  </div>
</template>

<script>
import { shopList } from "../../api/newShop/index";

function parseLayout(layout) {
  if (typeof layout === 'string') {
    try {
      return JSON.parse(layout);
    } catch (e) {
      return {};
    }
  }
  return layout || {};
}

export default {
  name: 'Banner',
  props: {
    layout: {
      type: [Object, String],
      default: () => ({})
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      bannerList: [],
      resLayout: '' // 保存接口返回的layout字符串
    }
  },
  mounted() {
    this.getShopList();
  },
  watch: {
    layout: {
      handler() {
        this.$forceUpdate();
      },
      deep: false
    }
  },
  computed: {
    parsedLayout() {
      try {
        return typeof this.resLayout === 'string' ? JSON.parse(this.resLayout) : (this.resLayout || {});
      } catch (e) {
        return {};
      }
    },
    bannerIndex() {
      let idx = this.parsedLayout?.banner_index;
      if (Array.isArray(idx)) return idx.map(Number);
      if (typeof idx === 'string') {
        try { const arr = JSON.parse(idx); if (Array.isArray(arr)) return arr.map(Number); } catch {}
      }
      if (typeof idx === 'number') return idx;
      return 1;
    },
    mainBanners() {
      // 只取前N张用于特殊布局
      if (Array.isArray(this.bannerIndex)) {
        const count = this.bannerIndex.flat().reduce((a, b) => a + b, 0);
        return this.bannerList.slice(0, count);
      } else if (typeof this.bannerIndex === 'number') {
        return this.bannerList.slice(0, 1);
      }
      return this.bannerList;
    },
    extraBanners() {
      // 超出部分用于全宽轮播
      if (Array.isArray(this.bannerIndex)) {
        const count = this.bannerIndex.flat().reduce((a, b) => a + b, 0);
        return this.bannerList.slice(count);
      } else if (typeof this.bannerIndex === 'number') {
        return this.bannerList.slice(1);
      }
      return [];
    },
    isType1() { // [1,1]
      return Array.isArray(this.bannerIndex) && this.bannerIndex[0] === 1 && this.bannerIndex[1] === 1;
    },
    isType2() { // [2,1]
      return Array.isArray(this.bannerIndex) && this.bannerIndex[0] === 2 && this.bannerIndex[1] === 1;
    },
    isType3() { // [1,2]
      return Array.isArray(this.bannerIndex) && this.bannerIndex[0] === 1 && this.bannerIndex[1] === 2;
    },
    groupSize() {
      if (this.isType1) return 2;
      if (this.isType2 || this.isType3) return 3;
      return 1;
    },
    bannerGroups() {
      const size = this.groupSize;
      const groups = [];
      let i = 0;
      while (i + size <= this.bannerList.length) {
        groups.push(this.bannerList.slice(i, i + size));
        i += size;
      }
      while (i < this.bannerList.length) {
        groups.push([this.bannerList[i]]);
        i++;
      }
      return groups;
    }
  },
  methods: {
    handleEditModeClick(event) {
      if (this.isEditMode) {
        event.preventDefault();
        event.stopPropagation();
      }
    },
    getFullImgUrl(thumb) {
      const baseUrl = getApp().globalData.baseUrl;
      return thumb.startsWith("http") ? thumb : baseUrl + thumb;
    },
    getShopList() {
      shopList().then(res => {
        if (res.code === 200) {
          this.bannerList = res.data.banner_index; // 图片数组
          this.resLayout = res.data.layout; // 保存layout字符串
        }
      }).catch(err => {
        console.error('获取 banner 失败：', err);
      });
    },
    // 处理点击事件
    handleClick(event) {
      // 检查是否在编辑模式下
      if (this.isEditMode) {
        // 编辑模式下，阻止默认行为
        event.preventDefault();
        event.stopPropagation();
        
        this.$emit('component-click', 'banner', {
          items: this.bannerList
        }, event);
      }
      // 非编辑模式下，允许正常的点击行为
    },
    // 更新配置
    updateConfig(config) {
      if (config && config.items) {
        this.bannerList = config.items;
      }
    }
  }
}
</script>

<style scoped>
.banner-container {
  margin-top: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
}

//.banner-container:hover {
//  transform: scale(1.02);
//  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
//}

.banner-placeholder {
  width: 95%;
  height: 110px;
  background: #e0e0e0;
  border-radius: 16px;
  margin: 0 0 16px .6rem;
}
</style>